package com.sen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sen.dto.TypeDTO;
import com.sen.entity.Book;
import com.sen.entity.Type;
import com.sen.mapper.TypeMapper;
import com.sen.service.BookService;
import com.sen.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.codegen.TypeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sen
 * @since 2021-03-13
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private BookService bookService;

    /**
     * 根据类别ID查询类别，用于更新某个类别前查询
     * @param id
     * @return
     */
    @Override
    public Type getTypeById(Integer id) {
        Type type = typeMapper.selectById(id);
        return type;
    }

    /**
     * 获取所有的类别列表
     * @return
     */
    @Override
    public List<Type> getTypeList(Integer cur, Integer size) {
        Page<Type> page = new Page<>(cur, size);
        Page<Type> typePage = typeMapper.selectPage(page, null);
        List<Type> typeList = typePage.getRecords();
        return typeList;
    }

    /**
     * 根据类别ID删除类别，删除前需要判断是否有该类别的书籍，如果有，则不允许删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteTypeById(Integer id) {
        List<Book> bookList = bookService.getBookListByTypeId(id);

        // 该类别书籍不为空，不能删除该类别，返回false
        if (!bookList.isEmpty()) {
            return false;
        }
        return this.removeById(id);
    }

    /**
     * 新增类别
     * @param typeDTO
     * @return
     */
    @Override
    public boolean saveType(TypeDTO typeDTO) {
        Type type = new Type();
        type.setTypeName(typeDTO.getTypeName());
        return this.save(type);
    }

    /**
     * 修改类别
     */
    @Override
    public boolean updateType(TypeDTO typeDTO) {
        Type type = new Type();
        type.setId(typeDTO.getId());
        type.setTypeName(typeDTO.getTypeName());
        return this.updateById(type);
    }

    /**
     * 模糊查询分类
     */
    @Override
    public List<Type> searchType(String key) {
        QueryWrapper<Type> wrapper = new QueryWrapper<>();
        wrapper.like("type_name", key);
        List<Type> typeList = typeMapper.selectList(wrapper);
        return typeList;
    }

}
